import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'state.dart';
import 'package:yp/services/api.dart';

import '../../../helper.dart';
import '../../../router.dart';

class SetPayPwdLogic extends GetxController {
  final state = SetPayPwdState();

  @override
  void onInit() {
    super.onInit();
    state.phone = SpUtil.getString('number');
  }

  queryUserInfo() {
    var userParams = {
      'access_token': SpUtil.getString('token'), // token
      'mobile': SpUtil.getString('number'),
    };
    Api.searchMember(userParams).listen((event) {
      if (event['code'] == 0) {
        var usrNo = event['usr_no'].toString();
        submit(usrNo);
      }
      EasyLoading.dismiss();
    });
  }

  //请求发送验证码
  void sendSms() {
    if (!state.verifyEnable) {
      return;
    }
    state.verifyEnable = false;
    var params = {"mobile": state.phone, "verify_code_type": "forgot"};
    Api.sendSms(params).listen((event) {
      if (event['code'] == 0) {
        toast("验证码已发送,请注意查收");
        state.smsData = event;
      } else {
        toast(event['message']);
        state.verifyEnable = true;
      }
      update();
    });

    state.timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (state.seconds == 0) {
        state.timer?.cancel();
        state.verifyText = '重新发送';
        state.seconds = 5;
        state.verifyEnable = true;
        update();
        return;
      }
      state.verifyEnable = false;
      state.seconds = --state.seconds;
      state.verifyText = "已发送${state.seconds}s";
      print("已发送${state.seconds}s");
      update();
    });
  }

  submitAction() {
    if (state.codeCtrl.text.isEmpty) {
      toast("请输入验证码");
      return;
    }

    if (state.smsData == null) {
      toast("请先获取验证码");
      return;
    }

    if (state.pwdCtrl.text.isEmpty) {
      toast("请输入支付密码");
      return;
    }
    if (state.pwdCtrl.text.length != 6) {
      toast("请输入6位支付密码");
      return;
    }
    EasyLoading.instance..userInteractions = false;
    EasyLoading.show();
    queryUserInfo();
  }

  submit(String usrNo) {
    var params = {
      "mobile": state.phone,
      'card_no': usrNo,
      'sms_verify_code': state.codeCtrl.text,
      'sms_verify_token': state.smsData['token'],
      'sms_verify_type': 'forgot',
      'new_password': state.pwdCtrl.text
    };
    Api.setPayPwd(params).listen((event) {
      if (event['code'] == 0) {
        Get.back(result: true);
      } else {
        toast(event['message']);
      }
      EasyLoading.dismiss();
    });
  }

  @override
  void dispose() {
    super.dispose();
    state.timer.cancel();
  }
}
